<template>
  <div class="l-rblock l-form-viewer" style="padding:10px 10px 50px 10px">
    <div class="l-auto-window" :class="{ 'only-tabs': onlyMap }">
      <el-tabs v-model="activeName" type="card" :before-leave="handleTabBeforeLeave">
        <template v-if="!onlyMap">
          <el-tab-pane class="l-tabs-container" :label="$t('基本信息')" name="tab0">
            <el-form :model="formData" :rules="rules" size="mini" labelPosition="top" labelWidth="110px" ref="form">
              <l-custom-form ref="CustomForm" :disabled="disabled" :columns="columns" :span="12">
                <template v-slot:constructionEntity="form">
                  <el-form-item label="建设单位" prop="constructionEntity">
                    <l-remote-select ref="RemoteSelect" v-model="form.constructionEntity" labelKey1="enterpriseName"
                      @change="changeConstruction" @remoteMethod="loadConstruction" :hasAdd="true"
                      :config="ConstructionConfig">
                    </l-remote-select>
                  </el-form-item>
                </template>
              </l-custom-form>
            </el-form>
          </el-tab-pane>
        </template>
        <el-tab-pane class="l-tabs-container tabs-map" :label="$t('项目位置')" name="tab1">
          <l-draw-map v-if="activeName == 'tab1'" ref="SetMap" :geoData="geoData" @getDrawData="getDrawData"></l-draw-map>
        </el-tab-pane>
        <el-tab-pane v-if="false" class="l-tabs-container tabs-map" :label="$t('电子档案')" name="tab2">
          <l-file-management v-if="activeName == 'tab2' && projectId" :projectID="projectId"
            :dirTableName="'plan_info'"></l-file-management>
        </el-tab-pane>
      </el-tabs>
      <div class="tab-btn">
        <el-button size="small" @click="handleClose">关闭</el-button>
        <template v-if="activeName == 'tab0' && !disabled">
          <el-button v-if="projectId" size="small" type="primary" @click="handleSave(true)"> 更新</el-button>
          <el-button v-else size="small" type="primary" @click="handleSave(false)">提交 </el-button>
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import formConfig from "./columns";
import config from "../UnitsManager/colmuns";
export default {
  components: {
  },
  props: {
    disabled: {
      type: Boolean,
      default: false,
    },
    onlyMap: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      fromEditing: false,

      ConstructionConfig: config,
      activeName: 'tab0',
      projectId: "",
      formData: formConfig.formData,
      rules: {
        projectName: [{ required: true, message: '请输入' }],
        projectTypeId: [{ required: true, message: '请输入' }],

      },
      columns: formConfig.formColmuns,
      // 空间数据
      geometry: "", // wkt格式
      geoData: {},   // goejson格式
      projectGeoId: '',  // 项目空间信息id
    };
  },
  computed: {
  },
  mounted() {
    this.init()

    this.lr_loadDataItem('unitType') // 单位类型
  },
  methods: {
    init() {
      if (this.$refs.CustomForm) {
        this.$refs.CustomForm.formData = this.formData
      }
    },

    // 重置表单
    resetForm() {
      this.$formClear(this.$refs.form)
      this.activeName = 'tab0'
      Object.assign(this.$data, this.$options.data())
      if (this.$refs.CustomForm) {
        this.$refs.CustomForm.formData = {}
      }
    },
    // 校验表单
    async validateForm() {
      if (!await this.$formValidateWraper(this.$refs.form)) {
        return false
      }
      return true
    },

    // 获取当前表单数据
    getForm() {
      this.formData = this.$refs.CustomForm.formData
      return this.formData
    },
    /** 加载项目信息   初始化表单 */
    async loadFormData(projectId) {
      this.projectId = projectId
      this.getGeoData() // 获取空间信息
      this.fromEditing = true
      const api = window.$crud("project");
      const data = await this.$awaitWraper(api.get(projectId))
      if (data) {
        // 项目信息
        for (const key in this.formData) {
          if (Object.prototype.hasOwnProperty.call(data, key)) {
            if (typeof data[key] === 'boolean') {
              data[key] = data[key].toString();
            }
          }
          this.formData[key] = data[key] || "";
        }
        if (this.$refs.CustomForm) {
          this.$refs.CustomForm.formData = this.formData
        }
        return true
      } else {
        return false
      }
    },

    /** 关闭表单 */
    handleClose() {
      this.$emit('close')
    },
    /** 提交 保存 事件 */
    async handleSave(isEdit) {
      if (await this.validateForm()) {
        const res = await this.saveForm(isEdit)
        if (res) {
          this.$message({
            type: 'success',
            message: '提交成功'
          })
          this.$emit('refresh')
        }
      }
    },
    /** 保存表单数据 */
    async saveForm(isEdit) {
      let postData = this.getForm()
      if (isEdit) {// 编辑
        const api = window.$crud("project");
        return await this.$awaitWraper(api.update(this.projectId, postData))
      } else { // 新增
        const api = window.$crud("project/info");
        return await this.$awaitWraper(api.add(postData))
      }
    },

    //#region 绘制
    /** 获取项目空间信息 */
    async getGeoData() {
      if (this.projectId) {
        const api = window.$crud("project/geography/list");
        const data = await this.$awaitWraper(api.getInfo({ projectId: this.projectId }))
        if (data && data.length) {
          this.projectGeoId = data[0].id
          var { parseFromWK } = require('@/core/util/wkt.js')
          this.geometry = data[0].geometry
          this.geoData = parseFromWK(data[0].geometry)
        }
      }
    },
    /** 绘制 获取绘制数据 */
    getDrawData(data) {
      var { convertToWK } = require('@/core/util/wkt.js')
      if (data.length) {
        var geojson = {
          'type': 'FeatureCollection',
          'features': data
        }
        this.geoData = geojson
        this.geometry = convertToWK(geojson)
        this.saveDraw({ geometry: this.geometry })
      } else {
        this.geometry = ""
        this.geoData = {}
        this.saveDraw({ geometry: this.geometry })
      }
    },
    /** 绘制保存 */
    async saveDraw({ geometry }) {
      await this.getGeoData() // 获取空间信息
      const postData = {
        projectId: this.projectId,
        geometry: geometry
      }
      var res = null
      if (this.projectGeoId) {
        // 编辑
        const api = window.$crud("project/geography");
        res = await this.$awaitWraper(api.update(this.projectGeoId, postData))
      } else {
        // 新增
        const api = window.$crud("project/geography/info");
        res = await this.$awaitWraper(api.add(postData))
      }
      if (res) {
        this.$message({
          type: 'success',
          message: '提交成功'
        })
        await this.getGeoData() // 获取空间信息
      }
    },

    //#endregion


    /** 表单切换校验 */
    handleTabBeforeLeave(activeName, oldActiveName) {
      // 判断业务id是否存在 即当前业务信息是否为编辑状态
      if (!this.projectId) {
        return new Promise((resolve, reject) => {
          if (oldActiveName == 'tab0') {
            this.$refs.form.validate((valid) => {
              if (valid) {
                this.$message({
                  message: '请点击提交完成新增！',
                  type: 'warning'
                });
                reject()
              }
              else {
                this.$message({
                  message: '请先填写完整信息！',
                  type: 'warning'
                });
                reject()
              }
            })
          }
        })
      }
    },

    //#region 建设单位选择
    /** 获取单位列表 */
    async loadConstruction(keyword, callback) {
      const api = window.$crud("ent/list");
      const data = await this.$awaitWraper(api.getInfo({ keyword: keyword, enterpriseType: 'construction' }));
      callback(data)
    },
    /** 下拉框 项目选择 change事件 */
    changeConstruction(e) {
      this.formData.constructionEntity = e.id
    },

    setSearchList(info) {
      this.$refs.RemoteSelect && this.$refs.RemoteSelect.setSearchList(info)
    }
    //#endregion



  }
}
</script>
<style lang="scss" scoped>
.l-auto-window {
  // height: calc(100% - 50px);
  height: 100%;
}

.tab-btn {
  position: absolute;
  bottom: -40px;
  right: 0px;
}

.l-tabs-container {
  padding-top: 16px !important;
}

.tabs-map {
  overflow-y: hidden !important;
}
</style>